# *** Artificial ARIMA
show.arima <- function(data,order,p) {
	train.samples=floor(length(data) * p)
	fit=arima(data[1:train.samples],order=order)
	pred=predict(fit,n.ahead=length(data)-train.samples)$pred
	error=data[(train.samples+1):length(data)]-pred
	pad=rep(NA,train.samples)
	matplot(
			cbind(
					data,
					c(data[1:train.samples]+fit$residuals,pred),
					c(fit$residuals,error)
			),
			typ='l',lty=1,pch=20,cex=0.3,cex.main=1,ylab=NA,
			main=sprintf("(p=%d,d=%d,q=%d)\nres2=%3.2f, aic=%3.2f",
					order[1],order[2],order[3],fit$sigma2,fit$loglik,fit$aic
			)
	)
	abline(v=train.samples,col=4)
	return(fit)
}

show.lm <- function(x,y,p) {
	train.samples=floor(length(x) * p)
	x.sample=x[1:train.samples]
	y.sample=y[1:train.samples]
	fit=lm(y.sample~x.sample)
	pred=predict(fit,newdata=y[(train.samples+1):length(y)],interval='prediction')
	error=y[(train.samples+1):length(y)]-pred
	pad=rep(NA,train.samples)
	matplot(x,
			cbind(
					y,
					c(fit$fitted.values,pred),
					c(fit$residuals,error)
			),
			typ='l',lty=1,pch=20,cex=0.3,cex.main=1,ylab=NA,
			main=sprintf("res2=%3.2f, aic=%3.2f",
					fit$sigma2,fit$loglik,fit$aic
			)
	)
	abline(v=train.samples,col=4)
	return(fit)
}

graphics.off()
n=50
x=0:(n-1)
y=cumsum(rep(rnorm(10),5))
y=y+runif(length(y))*0.5
#y=jitter(x,amount=1)
if (T) {
	windows()
	par(mfcol=c(2,4),mai=c(0.1,0.1,0.1,0.1)*4)
	plot(diff(y),typ='b',pch=20,cex=0.5,main='diff(y)')
	acf(y,main='ACF')
	pacf(y,main='PACF')
}

#windows()
p=0.5
fits=list()
#fits=c(fits,list(show.arima(y,order=c(p=1,d=1,q=0),p=p)))
#fits=c(fits,list(show.arima(y,order=c(p=1,d=1,q=1),p=p)))
fits=c(fits,list(show.arima(y,order=c(p=3,d=1,q=1),p=p)))
fits=c(fits,list(show.arima(y,order=c(p=3,d=2,q=1),p=p)))
fits=c(fits,list(show.arima(y,order=c(p=5,d=2,q=1),p=p)))
fits=c(fits,list(show.arima(y,order=c(p=5,d=2,q=2),p=p)))
fits=c(fits,list(show.arima(y,order=c(p=5,d=2,q=3),p=p)))
